/**
 * Copyright (C) 2011 Moss Computing <support@mosscomputing.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.oslef.format;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import org.oslef.csv.table.Row;
import org.oslef.csv.table.TableIterator;

/**
 * Provides a handy way to iterate over OSLEF records individually without
 * needing to hard-code the file names or directly refer to CSV libraries.
 */
public final class Inspector {
	
	public static final String
		LOANS_FILE = "loans.csv",
		INSTALLMENTS_FILE = "installments.csv",
		HISTORY_FILE = "history.csv";
	
	private final File oslefDir;

	public Inspector(File oslefDir) throws IOException {
		if (oslefDir == null) throw new NullPointerException();
		this.oslefDir = oslefDir;
	}
	
	public RecordIterator records(String fileName) throws IOException {
		File f = new File(oslefDir, fileName);
		TableIterator itr = new TableIterator(f);
		return new RecordIterator(itr);
	}
	
	public static final class RecordIterator implements Iterator<Record>, Iterable<Record> {
		
		private final TableIterator itr;
		
		public RecordIterator(TableIterator itr) {
			super();
			this.itr = itr;
		}

		public boolean hasNext() {
			return itr.hasNext();
		}
		
		public Record next() {
			Row row = itr.next();
			Record record = new MapRecord();
			for (String k : row.header()) {
				String v = row.get(k);
				if (StringUtil.nonEmpty(v)) record.put(k, v);
			}
			return record;
		}
		
		public void remove() {
			itr.remove();
		}
		
		public Iterator<Record> iterator() {
			return this;
		}
		
		public void close() throws IOException {
			itr.close();
		}
	}
}


